﻿using Common;
using Common.SerializationHelper;
using DeliveryManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using DeliveryManage.Controllers;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Concurrent;
using Antlr.Runtime.Misc;
using System.Threading.Tasks;

namespace DeliveryManage.Models
{
    public class OrderMassageHandler
    {
        public readonly static OrderMassageHandler Instance = new OrderMassageHandler();
        private OrderMassageHandler()
        { }
        private ConcurrentQueue<NewOrderQueueInfo> ListQueue = new ConcurrentQueue<NewOrderQueueInfo>();
        
        /// <summary>
        /// 加入到处理队列
        /// </summary>
        public void AddQueue(NewOrderQueueInfo queueInfo) //入列
        {
            ListQueue.Enqueue(queueInfo);
        }

        public void Start()//启动
        {
            Task.Run(() => { ThreadStartAsync(); });
        }

        private void ThreadStartAsync()
        {
            while (true)
            {
                try
                {
                    if (ListQueue.TryDequeue(out NewOrderQueueInfo item))
                    {
                        ScanQueue(item);
                    }
                }
                catch (Exception ex)
                {
                    // 异常处理
                    MvcApplication.AddLogsToTxt("反馈消息队列异常:" + ex.Message);
                    continue;
                }
                // 等待任务执行完成
                Thread.Sleep(1000);
            }

        }

        //要执行的方法
        private bool ScanQueue(NewOrderQueueInfo queueinfo)
        {
            //从队列中取出
            try
            {
                if (queueinfo != null)
                {
                    foreach (var item in MvcApplication.UserList)
                    {
                        MvcApplication.UserList[item.Key].NewOrderId = queueinfo.NewOrderId;
                    }
                    return true;
                }
            }
            catch (TimeoutException e) {
                MvcApplication.AddLogsToTxt("处理超时:" + e.Message);
                return false;
            }
            catch (Exception ex)
            {
                MvcApplication.AddLogsToTxt("异常:" + ex.Message);
                return false;
            }
            return true;
        }
    }

    //队列临时类
    public class NewOrderQueueInfo
    {
        /// <summary>
        /// 记录订单ID
        /// </summary>
        public int NewOrderId { get; set; }
    }
}